package com.ljq.shopgateway.config;

import com.alibaba.nacos.client.utils.StringUtils;
import lombok.Data;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 自定义年龄断言工厂
 * 当年龄在一定范围才能转发
 */
@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {


    public AgeRoutePredicateFactory() {
        super(AgeRoutePredicateFactory.Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("minAge", "maxAge");
    }

    @Override
    public Predicate<ServerWebExchange> apply(AgeRoutePredicateFactory.Config config) {

      return   exchange -> {
          String ageStr = exchange.getRequest().getQueryParams().getFirst("age");
          if (StringUtils.isNotEmpty(ageStr)) {
              int age = Integer.parseInt(ageStr);
              return age > config.getMinAge() && age < config.getMaxAge();
          }
          return false;
      };

       /* //接口式编程简化版
        return (ServerWebExchange serverWebExchange) -> {
            String ageStr = serverWebExchange.getRequest().getQueryParams().getFirst("age");
            if (StringUtils.isNotEmpty(ageStr)) {
                int age = Integer.parseInt(ageStr);
                return age > config.getMinAge() && age < config.getMaxAge();
            }
            return true;
        };*/
    }

    @Data
   public static class Config {

        private Integer minAge;
        private Integer maxAge;
    }
}
